import router from '@/router'
import store from '@/store'

import { getSessionItem } from './utils/token'
import { ACCESS_TOKEN, WEB_TITLE } from './variables/storageVariables'
import { addDynamicRoutes } from '@/router/permission'
const whiteRoutes = ['/login']
const loadingTime = 500

router.beforeEach(async (to, from, next) => {
  // debugger
  store.dispatch('progressLinear/toggleLoading', true)

  // 是否已经登录
  const hasToken = getSessionItem(ACCESS_TOKEN)
  // 页面标签名
  document.title = to.meta.title ? WEB_TITLE + ' - ' + to.meta.title : WEB_TITLE

  if (hasToken) {
    // debugger
    if (to.path === '/login') {
      next()
    } else {
      console.log(store.getters['user/permissions'], "store.getters['user/permissions']")
      const hasPermissions = store.getters['user/permissions'] && store.getters['user/permissions'].length > 0
      if (hasPermissions) {
        // 有权限放行
        next()
      } else {
        // 无权限
        try {
          // debugger
          await store.dispatch('user/getUserInfo')
          // const accessRoutes = []
          await addDynamicRoutes()

          router.push(to.path)
        } catch {
          // 重置权限
          await store.dispatch('user/resetAccessToken')
        }
      }
    }
    setTimeout(() => {
      store.dispatch('progressLinear/toggleLoading', false)
    }, loadingTime)
  } else {
    if (whiteRoutes.includes(to.path)) {
      next()
    } else {
      if (to.path.includes('redirect')) {
        next()
      } else {
        next('/login')
      }
    }
    setTimeout(() => {
      store.dispatch('progressLinear/toggleLoading', false)
    }, loadingTime)
  }
})
